package cn.edu.zafu.bigdata.x.cxy;

import java.util.Random;
import java.util.Scanner;

public class GuessNumberGame {

    // 最大猜测次数
    private static final int MAX_ATTEMPTS = 5;

    // 游戏主方法
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        boolean playAgain;

        // 多轮游戏循环
        do {
            int secretNumber = random.nextInt(100) + 1;  // 生成1到100之间的随机数
            int attemptsLeft = MAX_ATTEMPTS;
            boolean isGuessed = false;

            System.out.println("欢迎来到猜数字游戏！");
            System.out.println("有一个1到100之间的数字，你有" + MAX_ATTEMPTS + "次机会猜中它。");

            // 当前轮次游戏循环
            while (attemptsLeft > 0) {
                System.out.print("请输入你的猜测： ");
                int guess = scanner.nextInt();

                if (guess == secretNumber) {
                    System.out.println("恭喜你，猜中了！");
                    isGuessed = true;
                    break;
                } else if (guess > secretNumber) {
                    System.out.println("猜大了！");
                } else {
                    System.out.println("猜小了！");
                }

                attemptsLeft--;
                System.out.println("你还有 " + attemptsLeft + " 次机会。");
            }

            // 游戏结果提示
            if (!isGuessed) {
                System.out.println("很遗憾，你用完了所有机会。正确答案是：" + secretNumber);
            }

            // 提问是否再玩一轮
            System.out.print("你想再玩一轮吗？(y/n): ");
            char response = scanner.next().charAt(0);
            playAgain = (response == 'y' || response == 'Y');

        } while (playAgain);

        System.out.println("感谢你的参与，游戏结束！");
        scanner.close();
    }
}
